import { message } from "antd";
import MarkerClusterer from "bmaplib.markerclusterer";
import ownerOn from '../../assets/images/icon/position.png'

interface IMap {
  container: string,
  location?: Array<string | number>,
  enableMapClick?: Boolean,
  defaultLoction?: Array<string | number>,
  level?: number,
  style?: Object,
  overviewMapControl?: Boolean,
  enableScrollWheelZoom?: Boolean,
  disable3DBuilding?: Boolean,
}


export function loadJScript(url) {
  var script = document.createElement("script");
  script.type = "text/javascript";
  script.src = url;
  document.body.appendChild(script);
}

export function createMap({
  container = "",
  location = [],
  enableMapClick = false,
  defaultLoction = [121.618835, 29.920698],
  level = 20,
  style,
  overviewMapControl = true,
  enableScrollWheelZoom = true,
  disable3DBuilding = true
}: IMap): any {
  let map, point;

  if (window.BMap && (typeof window.BMap.Map === "function")) {
    map = new window.BMap.Map(container, {
      enableMapClick: enableMapClick
    });
    point = new window.BMap.Point(
      location[0] || defaultLoction[0],
      location[1] || defaultLoction[1]
    );

    map.centerAndZoom(point, level);
    if (overviewMapControl) {
      map.addControl(new window.BMap.OverviewMapControl()); //添加缩略地图控件
    }
    if (enableScrollWheelZoom) {
      map.enableScrollWheelZoom(); //启用滚轮放大缩小
    }
    if (disable3DBuilding) {
      map.disable3DBuilding();
    }
    if (style) {
      map.setMapStyle({
        styleJson: style
      });
    }

  } else {
    message.error("网络问题请刷新");
  }

  return map;
}

export function getSinglePoints(map, location) {
  if (!window.BMap || (typeof window.BMap.Map !== "function")) {
    message.error("网络问题请刷新");
    return;
  }

  // let location = poi.location.split(',');
  const point = new window.BMap.Point(+location[0], +location[1]);
  const myIcon = new window.BMap.Icon(ownerOn, new window.BMap.Size(50, 50));
  const marker = new window.BMap.Marker(point, { icon: myIcon });
  let onlineArr = [];
  onlineArr.push(marker)
  new MarkerClusterer(map, {
    markers: onlineArr
  });
}

export function deletePoint(map, markers) {
  const { marker = [] } = markers;
  for (let i = 0; i <= marker.length; i++) {
    map.clearOverlays(marker[i])
  }
}

export function moveToPoint(map, location, level) {
  let point = new window.BMap.Point(location[0], location[1]);
  map.centerAndZoom(point, level);
}

